import { ref, computed, nextTick } from 'vue'
export default function (todos) {
	let originTitle = ''
	// 响应式数据，当前正在修改哪个
	const editingTodo = ref(null)
	// 什么情况会进入修改？
	const editTodo = function (todo, e) {
		originTitle = todo.title
		editingTodo.value = todo
		const focusEle = e.currentTarget.querySelector('.edit')
		nextTick(() => {
			focusEle.focus()
		})
	}
	// 完成修改函数
	const doneTodo = (todo) => {
		editingTodo.value = null
		// 完成修改时
		const title = todo.title.trim()
		if (title) {
			todo.title = title
		} else {
			todos.value.splice(todos.value.indexOf(todo), 1)
		}
	}
	// 取消修改
	const cancelEdit = (todo) => {
		editingTodo.value = null
		todo.title = originTitle
	}
	// 全选完成
	const handleAllSelect = () => {
		let count = 0
		todos.value.forEach((todo) => {
			if (todo.completed) {
				count++
			}
		})
		if (count === todos.value.length) {
			// 如果已经权限，则取消全部
			todos.value.forEach((it) => {
				it.completed = false
			})
		} else {
			todos.value.forEach((it) => {
				it.completed = true
			})
		}
	}
	// 响应式数据：是否全部选中
	const allSelected = computed(() => {
		let flag = true
		todos.value.forEach((it) => {
			if (it.completed === false) {
				flag = false
			}
		})
		return flag
	})
	return { editingTodo, editTodo, doneTodo, cancelEdit, handleAllSelect, allSelected }
}
